package LeetCode;

public class countDigitOne {
    
    private int dNum = 0;
    private int[] data;
    private int[] size;
    public int count(int n) {
        int num = n;
        int value = 0;
        if (n <= 0) {
            return 0;
        }
        dNum = n;
        int len = getLen(n);
        data = new int[len];
        size = new int[len];
        size[0] = 1;
        for (int i = 0; i < len; i++) {
            data[i] = num % 10;
            num = num / 10;
            if (i > 0) {
                size[i] = size[i-1] * 10 + (int)Math.pow(10, i);
            }
        }
        value = digit(len -1);
        return value;
    }
    
    private int digit(int index) {
        if (index == 0) {
            if (data[index] == 0) return 0;
            return 1;
        }
        else {
            int base = size[index-1];
            int d1 = (data[index]) * base;
            int d2 = digit(index -1);
            if (data[index] > 1) {
                d1 += (int)Math.pow(10, index);
                d1 += d2;
            }
            else if(data[index] == 1){
                d1 += (getNum(index) + 1 + d2);
            }
            else {
                d1 += d2;
            }
            return d1;
        }
    }
    private int getNum(int n) {
        int d = 0;
        for (int i = n - 1; i >= 0; i--) {
            d += data[i];
            if (i != 0) {
                d = d * 10;
            }
        }
        return d;
    }
    private int getLen(int n) {
        int len = 0;
        String str = Integer.toString(n);
        len = str.length();
        return len;
    }
    public static void main(String[] args) {
        countDigitOne cd = new countDigitOne();
        int num = cd.count(11);
        System.out.println("digit one count is " + num);
    }
}
